package game.module.shop.dao;

import game.common.BeanTool;
import game.constants.GameConstant;
import game.module.shop.bean.ShopEntity;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

@Component
public class ShopCache {

	public static final Logger logger = LoggerFactory.getLogger(ShopCache.class);

	@Autowired
	private CacheManager cacheManager;

	@Autowired
	private ShopDao shopDao;

	@PostConstruct
	public void reload() {
		try {
			initShopTemplate();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	@SuppressWarnings("unchecked")
	private void initShopTemplate() throws Exception {
		List<ShopEntity> tplList = shopDao.getAllTemplate();
		Cache cache = cacheManager.getCache(GameConstant.CACHE_SHOP_TEMPLATE);
		ValueWrapper idKeyGoods = cache.get(GameConstant.CACHE_SHOP_KEY_ID_MAP);
		Map<Integer, ShopEntity> idKeyShopMap = null;
		if (idKeyGoods != null) {
			idKeyShopMap = (Map<Integer, ShopEntity>) idKeyGoods.get();
		} else {
			idKeyShopMap = new HashMap<Integer, ShopEntity>();
			cache.put(GameConstant.CACHE_SHOP_KEY_ID_MAP, idKeyShopMap);
		}
		BeanTool.addOrUpdate(idKeyShopMap, tplList, "id");
	}

	@SuppressWarnings("unchecked")
	public Collection<ShopEntity> getShopEntityAll() {
		Cache cache = cacheManager.getCache(GameConstant.CACHE_SHOP_TEMPLATE);
		ValueWrapper idKeyGoods = cache.get(GameConstant.CACHE_SHOP_KEY_ID_MAP);
		return ((Map<Integer, ShopEntity>) idKeyGoods.get()).values();
	}

	@SuppressWarnings("unchecked")
	public ShopEntity getShopEntity(int id) {
		Cache cache = cacheManager.getCache(GameConstant.CACHE_SHOP_TEMPLATE);
		ValueWrapper idKeyGoods = cache.get(GameConstant.CACHE_SHOP_KEY_ID_MAP);
		return ((Map<Integer, ShopEntity>) idKeyGoods.get()).get(id);
	}

}
